//
//  XQOrderDetailController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/4.
//

import UIKit

class XQOrderDetailController: XQBaseController {
    
    var popHandle: ((String?) -> Void)?
    
    private var orderDetailModel : XQOrderDetailModel?
    
    private lazy var scrollView : UIScrollView = {
        let scrollView = UIScrollView()
        return scrollView
    }()
    
    private lazy var mainView : UIView = {
        let v = UIView()
        return v
    }()

    private lazy var topView : XQOrderDetailTopView = {
        let view = XQOrderDetailTopView()
        return view
    }()
    
    private lazy var tableView : UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = false
        tableView.register(XQOrderDetailCell.self, forCellReuseIdentifier: "XQOrderDetailCell")
        
        return tableView
    }()
    
    private lazy var applyBtn : UIButton = {
        let btn = UIButton()
        btn.isHidden = true
        btn.backgroundColor = .mainTextColor
        btn.layer.cornerRadius = 29
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        btn.addTarget(self, action: #selector(applyClick), for: .touchUpInside)
        return btn
    }()
    
    private lazy var protocolView : XQLoginProtocolView = {
        let view = XQLoginProtocolView()
        view.isHidden = true
        view.protocolClickHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.protocolClick()
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        makeNav()
        makeUI()
        makeConstraints()
        
        XQHud.showLoading(controller: self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        refreshData()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .darkContent
    }
    
    private func makeNav() {
        self.backIcon = "black_back"
    }
    
    private func makeUI() {
        self.view.backgroundColor = .white
        self.view.addSubview(self.scrollView)
        self.scrollView.addSubview(self.mainView)
        self.mainView.addSubview(self.topView)
        self.mainView.addSubview(self.tableView)
        self.mainView.addSubview(self.applyBtn)
        self.mainView.addSubview(self.protocolView)
    }
    
    private func makeConstraints() {
        self.scrollView.snp.makeConstraints { make in
            make.top.equalTo(UIDevice.xq_statusHeight() + 51)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-UIDevice.xq_bottomSafeMargin())
        }
        
        self.mainView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(UIDevice.xq_width())
        }
        
        self.topView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(222)
        }
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.topView.snp.bottom).offset(10)
            make.left.right.equalTo(0)
            make.height.equalTo(0)
        }
        self.applyBtn.snp.makeConstraints { make in
            make.top.equalTo(self.tableView.snp.bottom).offset(32)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(54)
        }
        self.protocolView.snp.makeConstraints { make in
            make.top.equalTo(self.applyBtn.snp.bottom).offset(20)
            make.left.equalTo(29)
            make.right.equalTo(0)
            make.height.equalTo(20)
            make.bottom.equalTo(-16)
        }
    }
    
    private func refreshData() {
        let params : [String : String] = ["taxes" : self.orderId]
        
        XQNetworkManager.shared.postRequest(url: "/figures/promotional", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            
            if response?.object == 0 {
                
                if let model = XQOrderDetailModel.deserialize(from: response?.procedure) {
                    srongify.orderDetailModel = model
                    
                    srongify.updatePageData()
                    srongify.updateTableViewH()
                    
                    srongify.updateProtocolView()
                    
                }
            }
        }
    }
    
    private func updatePageData() {
        self.applyBtn.isHidden = false
        self.navTitle = orderDetailModel?.increasing?.flashlight ?? ""
        self.topView.model = orderDetailModel?.increasing
        self.applyBtn.setTitle(orderDetailModel?.increasing?.tested, for: .normal)
    }
    
    private func updateTableViewH() {
        if let propublica = orderDetailModel?.propublica {
            self.tableView.snp.updateConstraints { make in
                make.height.equalTo(propublica.count * 68)
            }
        }
        self.tableView.reloadData()
    }
    
    private func updateProtocolView() {
        guard let collectively = orderDetailModel?.collectively else {return}
        
        let title : String? = collectively.accessing
        
        if let url = title,!url.isEmpty {
            
            self.protocolView.isHidden = false
            
            let list = url.components(separatedBy: "||")
            
            if list.count == 2 {
                self.protocolView.prefixStr = list[0]
                self.protocolView.suffixStr = list[1]
            }
            
            self.protocolView.snp.updateConstraints { make in
                make.top.equalTo(self.applyBtn.snp.bottom).offset(20)
                make.height.equalTo(20)
            }
        }else {
            self.protocolView.isHidden = true
            self.protocolView.snp.updateConstraints { make in
                make.top.equalTo(self.applyBtn.snp.bottom).offset(0)
                make.height.equalTo(0)
            }
        }
    }
    
    @objc private func applyClick() {
        guard let frequently = orderDetailModel?.frequently else {return}
        
        if frequently.discretion?.count != 0 {
            didSelectNextController(title: frequently.accessing, className: frequently.discretion, url: frequently.measured)
            return
        }
        
        if needCheckPricacyBool() {
            XQHud.showToast(message: "Please read and agree to the Privacy Policy")
            return
        }
        
        let experience = orderDetailModel?.increasing?.accessible ?? ""
        
        var params : [String : String] = [
            "experience" : experience,
            "governments" : orderDetailModel?.increasing?.governments ?? "",
            "educationed" : orderDetailModel?.increasing?.educationed ?? "",
        ]
        
        if let account = orderDetailModel?.increasing?.account {
            params["account"] = "\(account)"
        }
        
        XQHud.showLoading(controller: self)
        XQNetworkManager.shared.postRequest(url: "/figures/annual", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            
            if (response?.object == 0) {
                
                srongify.notifyRisk(experience: experience)
                
                if let map = response?.procedure {
                    srongify.backController(url: map["measured"] as? String)
                }
            }else {
                XQHud.showToast(message: response?.patients ?? "Network Connection Error")
            }
        }
    }
    
    private func backController(url : String?) {
        popHandle?(url)
    }
    
    
    private func needCheckPricacyBool() -> Bool {
        return !self.protocolView.isHidden && !self.protocolView.radioBtn.isSelected
    }
    
    private func notifyRisk(experience : String) {
        let time = XQTimeTool.nowTime()
        XQAnalysisManager.shared.notifyRisk(numberType: "9", longitude: self.longitude, latitude: self.latitude, startT: time, endT: time, orderId: experience)
    }
}


extension XQOrderDetailController : UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return orderDetailModel?.propublica?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "XQOrderDetailCell", for: indexPath) as! XQOrderDetailCell
        
        if let propublica = orderDetailModel?.propublica {
            if (indexPath.row < propublica.count) {
                cell.model = propublica[indexPath.row]
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let propublica = orderDetailModel?.propublica else {return}
        
        if (indexPath.row >= propublica.count) {return}
        
        let m : XQOrderDetailPropublicaModel = propublica[indexPath.row]
        
        if (m.orders == 1) {
            didSelectNextController(title: m.accessing, className: m.discretion, url: m.measured)
            return
        }
        
        guard let frequently = orderDetailModel?.frequently else {return}
        
        if frequently.discretion?.count != 0 {
            didSelectNextController(title: frequently.accessing, className: frequently.discretion, url: frequently.measured)
        }
            
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 68
    }
    
    
    private func protocolClick() {
        guard let protocolStr = orderDetailModel?.collectively?.sent else {return}
        
        if protocolStr.isEmpty {return}
        
        XQRouteTool.jumpController(controller: self, url: protocolStr)
    }

    private func didSelectNextController(title : String?, className : String?, url : String?) {
        
        var baseController : XQBaseController?
        
        switch className {
        case "adriana":
            baseController = XQOrderDetailPublicController()
            break
        case "adrianb":
            baseController = XQOrderDetailPersonalController()
            break
        case "adrianc":
            baseController = XQOrderDetailJobController()
            break
        case "adriand":
            baseController = XQOrderDetailEmergencyController()
            break
        case "adriane":
            baseController = getWebController(url: url)
            break
        default:
            break
        }
        jumpOrderDetailController(controller: baseController,title: title)
    }
    
    private func getWebController(url : String?) -> XQBaseController? {
        guard let urlName = url else {return nil}
        let vc = XQWebController()
        vc.url = XQNetworkManager.shared.getWebUrlAbsolutePath(path:urlName)
        return vc
    }
    
    private func jumpOrderDetailController(controller : XQBaseController?,title : String?) {
        guard let vc = controller else {return}
        
        vc.orderId = self.orderId
        vc.navTitle = title ?? ""
        vc.navTitleColor = .white
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
